// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package adwords.axis.v201109_1.reporting;

import com.google.api.ads.adwords.axis.utils.v201109_1.ReportDownloader;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;
import com.google.api.ads.common.lib.auth.ClientLoginTokens;
import com.google.api.ads.common.lib.utils.Streams;

import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;

/**
 * This example downloads a defined report.
 *
 * Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 *
 * @author Kevin Winter
 */
public class DownloadDefinedReport {

  public static void main(String[] args) throws Exception {
    // Get a ClientLogin AuthToken.
    String clientLoginToken = new ClientLoginTokens.Builder()
        .forApi(ClientLoginTokens.Api.ADWORDS)
        .fromFile()
        .build()
        .requestToken();

    // Construct an AdWordsSession.
    AdWordsSession session =
        new AdWordsSession.Builder().fromFile().withClientLoginToken(clientLoginToken).build();

    // Location to download report to.
    String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";
    long reportDefinitionId = Long.parseLong("INSERT_REPORT_DEFINITION_ID_HERE");

    runExample(session, reportDefinitionId, reportFile);
  }

  static void runExample(AdWordsSession session, long reportDefinitionId, String reportFile)
      throws Exception {
    ReportDownloadResponse response =
        new ReportDownloader(session).downloadReport(reportDefinitionId);
    if (response.getHttpStatus() == HttpURLConnection.HTTP_OK) {
      FileOutputStream fos = new FileOutputStream(new File(reportFile));
      Streams.copy(response.getInputStream(), fos);
      fos.close();
      System.out.println("Report successfully downloaded: " + reportFile);
    } else {
      System.out.println("Report was not downloaded. " + response.getHttpStatus() + ": "
          + response.getHttpResponseMessage());
    }
  }
}
